package com.erf.handler.server;

import com.erf.session.Session;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhangzy
 * @date 2022/7/5
 */
@Slf4j
@ChannelHandler.Sharable
public class BaseServerChannelDuplexHandler extends ChannelDuplexHandler {

    /**
     * 连接建立成功
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.debug("client:"+channel.id().asShortText()+" is connected");
    }

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        try {
            //连接断开断开
            String userName = ctx.channel().attr(LoginRequestHandler.KEY).get();
            String channelId = ctx.channel().id().asShortText();
            Session.remove(userName,channelId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.close(ctx, promise);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        try {
            //程序异常或被强制断开
            String userName = ctx.channel().attr(LoginRequestHandler.KEY).get();
            String channelId = ctx.channel().id().asShortText();
            Session.remove(userName,channelId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.exceptionCaught(ctx, cause);
    }
}
